package cn.dakaqi.utils.encryption;

import org.apache.commons.codec.digest.DigestUtils;

import java.security.MessageDigest;

public class EncryptionUtil {
    private final static String hexDigits[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};

    private String algorithm;

    public EncryptionUtil(String algorithm) {
        this.algorithm = algorithm;
    }

    /**
     * 加密
     *
     * @param rawPass 加密字段
     * @return 加密后字段
     */
    public String encode(String rawPass) {
        String result = null;
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            //加密后的字符串
            result = byteArrayToHexString(md.digest(rawPass.getBytes("utf-8")));
        } catch (Exception ignored) {
        }
        return result;
    }

    /**
     * 判断加密前后字符串是否相等
     *
     * @param encPass 加密后字符串
     * @param rawPass 加密前字符串
     * @return 结果
     */
    public boolean isPasswordValid(String encPass, String rawPass) {
        String pass1 = "" + encPass;
        String pass2 = encode(rawPass);

        return pass1.equals(pass2);
    }

    /**
     * 转换字节数组为16进制字串
     *
     * @param b 字节数组
     * @return 16进制字串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (byte aB : b) {
            resultSb.append(byteToHexString(aB));
        }
        return resultSb.toString();
    }

    /**
     * byte对象转换为String
     *
     * @param b byte对象
     * @return String
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static void main(String[] args) {
        EncryptionUtil encryptionUtil = new EncryptionUtil("MD5");
        String encode = encryptionUtil.encode("test");
        System.out.println(encode);
        boolean passwordValid = encryptionUtil.isPasswordValid("083A8DB3FF5B9B4ECE3EF2BDE03226C8", "test");
        System.out.println(passwordValid);


        EncryptionUtil encoderSha = new EncryptionUtil("SHA");
        String pass2 = encoderSha.encode("test");
        System.out.println(pass2);
        boolean passwordValid2 = encoderSha.isPasswordValid("1E4346DCB54C1444E91668E04B8CA4F74F42958E", "test");
        System.out.println(passwordValid2);

        String string = DigestUtils.md5Hex(pass2).toUpperCase();
        System.out.println(string);
    }
}
